const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {

  const wxContext = cloud.getWXContext()  
  const timestamp = event.timestamp
  // const res = await db.collection("user").where({openid:wxContext.OPENID,status:0}).get() 为什么要限定status:0?
const res = await db.collection("user").where({openid:wxContext.OPENID}).get()
console.log(res)
  if(res.data.length == 0)
  {
      return {
        code:401,
        data:{},
        msg:"have not login"
      }
  }
  let sid = res.data[0].sid
  let QRcode = null
  let timeTable = null 

  // if(timestamp >= new Date().valueOf() + 7200000) //先注释以便于测试
  // {
  //   return {
  //     code:404,
  //     data:{},
  //     // msg:"too early"
  //     msg:'太早了，预约时间前2小时内开放查询'
  //   }
  // }

  const order = await db.collection("order").where({
    timestamp:timestamp,
    sid:sid,
    state:0   
  }).get()

  if(order.data.length == 0)
  {
    return {
      code:404,
      data:{},
      // msg:"can not find the order"
      msg:"申请尚未通过"
    }
  }
  const result = await Promise.all([
    db.collection("QRcode").where({timestamp:timestamp}).get(),
    db.collection("timeTable").where({timestamp:timestamp}).get()
  ])
  
  timeTable = result[1].data
  if(timeTable.length > 0 && timeTable[0].isOpen)
  {
    QRcode = result[0].data
    if(QRcode.length == 0)
    {
        return {
          code:404,
          data:{},
          // msg:"can not find the QRcode",
          msg:"管理员未上传二维码"
        }
    }
    else
    {
      return {
        code:200,
        data:{
          path:QRcode[0].path,
        },
        msg:"success"
      }
    }
  }
  else
  {
    if(timeTable.length > 0)
    {
      return {
        code:404,
        data:{
          detail:timeTable[0]
        },
        msg:"the time table is not open"
      }
    }
    else
    {
      return {
        code:404,
        data:{},
        msg:"the time table is not created"
      }
    }
    
  }

};
